package com.sync.data.job.user;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.sync.data.ievent.entity.IeventBasePositionEmployee;
import com.sync.data.ievent.repository.IeventBasePositionEmployeeRepository;
import com.sync.data.mce.entity.MceBasePositionEmployee;
import com.sync.data.mce.repository.MceBasePositionEmployeeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.data.RepositoryItemReader;
import org.springframework.batch.item.database.JpaItemWriter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.PlatformTransactionManager;

import java.util.Collections;
import java.util.Date;

@Configuration
@EnableBatchProcessing
@RequiredArgsConstructor
public class PositionEmployeeSyncBatchJob {


    private final JobBuilderFactory jobBuilderFactory;

    private final StepBuilderFactory stepBuilderFactory;

    private final MceBasePositionEmployeeRepository mceBasePositionEmployeeRepository;

    private final IeventBasePositionEmployeeRepository ieventBasePositionEmployeeRepository;

    private final PlatformTransactionManager transactionManagerIevent;

    private final JpaItemWriter<IeventBasePositionEmployee> ieventBasePositionEmployeeJpaItemWriter;

    // 批处理大小
    private static final int CHUNK_SIZE = 100;

//    @Bean
//    public Job positionEmployeeSyncJob() {
//        return jobBuilderFactory.get("positionEmployeeSyncJob")
//                .incrementer(new RunIdIncrementer())
//                .start(syncPositionEmployeeStep())
//                .build();
//    }

//    @Bean
//    public Step prepareWorkNoSetStep() {
//        return stepBuilderFactory.get("prepareWorkNoSetStep")
//                .tasklet((contribution, chunkContext) -> {
//                    // 只存储关键信息，而不是整个集合
//                    int workNoCount = ieventBasePositionRepository.countDistinctWorkNos();
//
//                    // 存储统计信息而不是完整集合
//                    chunkContext.getStepContext()
//                            .getStepExecution()
//                            .getJobExecution()
//                            .getExecutionContext()
//                            .put("workNoCount", workNoCount);
//
//                    // 返回最小必要信息
//                    return RepeatStatus.FINISHED;
//                })
//                .build();
//    }

    @Bean
    public Step syncPositionEmployeeStep() {
        return stepBuilderFactory.get("syncPositionEmployeeStep")
                .<MceBasePositionEmployee, IeventBasePositionEmployee>chunk(CHUNK_SIZE)
                .reader(mceBasePositionEmployeeItemReader())
                .processor(positionEmployeeSyncProcessor())
                .writer(ieventBasePositionEmployeeJpaItemWriter)
                .transactionManager(transactionManagerIevent)
                .build();
    }

    public ItemReader<MceBasePositionEmployee> mceBasePositionEmployeeItemReader() {
        RepositoryItemReader<MceBasePositionEmployee> reader = new RepositoryItemReader<>();
        reader.setRepository(mceBasePositionEmployeeRepository);
        reader.setMethodName("findAll");
        reader.setSort(Collections.singletonMap("id", Sort.Direction.ASC));
        reader.setPageSize(CHUNK_SIZE);
        return reader;
    }

    public ItemProcessor<MceBasePositionEmployee, IeventBasePositionEmployee> positionEmployeeSyncProcessor() {
        return mceBasePositionEmployee -> {

            IeventBasePositionEmployee ieventBasePositionEmployee = ieventBasePositionEmployeeRepository.findById(mceBasePositionEmployee.getId()).orElse(null);

            if (ieventBasePositionEmployee == null) {
                ieventBasePositionEmployee = new IeventBasePositionEmployee();
                ieventBasePositionEmployee.setCreateTime(new Date());
            }

            BeanUtil.copyProperties(mceBasePositionEmployee, ieventBasePositionEmployee , CopyOptions.create().ignoreError().ignoreNullValue().setIgnoreProperties("updateTime","createTime"));
            ieventBasePositionEmployee.setDelFlag("0");
            ieventBasePositionEmployee.setUpdateTime(new Date());
            return ieventBasePositionEmployee;
        };
    }

}